import create from 'zustand'
import createVanilla from 'zustand/vanilla'
import { subscribeWithSelector } from 'zustand/middleware'
import { IKisItem, kisOPerationList, kisItemTranslator } from './translator'
import { fetchGetListDevices } from '@/api/manager/ai'
import { useMccStore } from '../../store'
import { uniqBy } from 'lodash-es'

const initialState = {
	isOpen: false, // 是否打开，开始轮询
	kisList: [], // 可以远程开机的列表
	kisOperation: { record: false, sign: false, subtitle: false }, // 操作按钮列表
}
type AIStore = aiState & {
	update: (d: Partial<aiState>) => void
	fetchInit: () => void // 获取可开机终端
	ws_mcc_mt_kis_devices: (
		mts: {
			mt_key: string
			mt_id: string
		}[]
	) => void
}
interface aiState {
	isOpen: boolean
	kisList: IKisItem[]
	kisOperation: kisOPerationList
}
export const store = createVanilla<AIStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => {
			set({ ...d })
		},
		reset: () => set(initialState),
		fetchInit: async () => {
			let initKisList: IKisItem[] = []
			const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
			const result = await fetchGetListDevices(meetingMoid)
			if (result) {
				let mt_keys = result.map((x) => x.mt_key)
				initKisList = kisItemTranslator(mt_keys)
			}
			set({ kisList: initKisList })
		},
		ws_mcc_mt_kis_devices: (mts) => {
			const kisList = get().kisList
			let mtKeys = mts.map((x) => x.mt_key)
			let _arr = kisItemTranslator(mtKeys)
			let result = uniqBy([..._arr, ...kisList], (val) => val.mtKey)
			set({ kisList: result })
		},
	}))
)
export const useAIStore = create(store)
